<?php
declare (strict_types=1);

namespace app\controller;
use \app\admin\model\Comment as Comments;
class Comment extends IndexBase
{
    public function add()
    {
        $data=$this->request->param();
        $ip=$this->request->ip();
        $avatar='/static/picture/tx'.mt_rand(1,8).'.jpg';
        if( !captcha_check($data['captcha'] ))
        {
            return xjson(404,'验证码填写错误');
        }
        //查询最近当天的发言是否已经超过十个
        $comment_count=new Comments();
        $count=$comment_count->where('ip',$ip)->whereDay('create_time','today')->count('id');
        if($count>=10){
            return xjson(405,'当日发言已到达上限,明天再来！');
        }
        //两次发言间隔不能低于10秒
        $recent_comment=$comment_count->field('create_time')->where('ip',$ip)->order('create_time','desc')->find();
        if(!$recent_comment->isEmpty()&&time()-strtotime($recent_comment->create_time)<10){
            return xjson(406,'两次发言间隔不能低于十秒！');
        }
        $data=array('news_id'=>$data['news_id'],
            'username'=>$data['username']
            ,'avatar'=>$avatar
            ,'content'=>$data['content']
            ,'status'=>1
            ,'ip'=>$ip
        );
        $comment=new Comments();
        $res=$comment->save($data);
        if($res){
            return xjson();
        }else{
            return xjson(500,'提交失败！');
        }
    }
}
